import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { MessageBox, Message } from 'element-ui'


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        token: getToken(),
        userInfo: '',
        isShowHeadFoot: false
    },
    getters: {
        token: state => state.token,
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        RESET_STATE: (state) => {
            Object.assign(state, state)
        },
        SET_USERINFO: (state, userInfo) => {
            state.userInfo = userInfo
        },
        SER_ISSHOWHEADFOOT: (state, data) => {
            state.isShowHeadFoot = data
        },
    },
    actions: {
        changeShowHeadFoot({ commit }, data) {
            commit('SER_ISSHOWHEADFOOT', data)
        },
        login({ commit }, userInfo) {
            const { username, password } = userInfo
            return new Promise((resolve, reject) => {
                login({ username: username.trim(), password: password }).then(response => {
                    console.log(2222, response);
                    if (response && response.code === 200) {
                        const { data } = response
                        commit('SET_TOKEN', data.jwt)
                        setToken(data.jwt)
                        resolve()
                    } else {
                        Message({
                            message: '登录失败！',
                            type: 'error',
                            duration: 1000
                        })
                        reject()
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        getInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getInfo(state.token).then(response => {
                    const { data } = response
                    if (!data) {
                        return reject('登录失败，请重新登录！')
                    }
                    commit('SET_USERINFO', data)
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        logout({ commit, state }) {
            removeToken() // must remove  token  first
            resetRouter()
            commit('RESET_STATE')
        },
        // remove token
        resetToken({ commit }) {
            return new Promise(resolve => {
                removeToken() // must remove  token  first
                commit('RESET_STATE')
                resolve()
            })
        }
    },
    modules: {
    }
})
export default store